package com.zx.mes.hyl.upms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.mes.controller.BaseController;
import com.zx.mes.hyl.upms.entity.SysMenu;
import com.zx.mes.hyl.upms.entity.SysRoleMenu;
import com.zx.mes.hyl.upms.entity.SysUser;
import com.zx.mes.hyl.upms.pagemodel.TreeNode;
import com.zx.mes.hyl.upms.service.SysMenuService;
import com.zx.mes.hyl.upms.service.SysRoleMenuService;
import com.zx.mes.response.ObjectRestResponse;
import com.zx.mes.response.TableResultResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 华云龙
 * @since 2018-07-09
 */
@CrossOrigin
@RestController
@RequestMapping("/sysMenu")
public class SysMenuController extends BaseController<SysMenuService,SysMenu> {

    private final SysRoleMenuService sysRoleMenuService;

    @Autowired
    public SysMenuController(SysRoleMenuService sysRoleMenuService) {
        this.sysRoleMenuService = sysRoleMenuService;
    }

    @Override
    public ObjectRestResponse<SysMenu> add(@RequestBody SysMenu sysMenu) {

        sysMenu.setId(UUID.randomUUID().toString());
        if (StringUtils.isBlank(sysMenu.getPid())) {
            sysMenu.setPid(null);
        }
        return super.add(sysMenu);
    }

    @Override
    public ObjectRestResponse<SysMenu> update(@RequestBody SysMenu sysMenu) {
        return super.update(sysMenu);
    }

    @Override
    public TableResultResponse<SysMenu> list(@RequestParam Map<String, Object> params, SysMenu sysMenu) {
        int page = Integer.valueOf(params.get("page").toString());
        int limit = Integer.valueOf(params.get("limit").toString());

        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        if (sysMenu != null && StringUtils.isNotBlank(sysMenu.getName())) {
            wrapper.like("name", sysMenu.getName());

        }


        List<SysMenu> list = biz.page(new Page(page, limit),wrapper).getRecords();
        TableResultResponse<SysMenu > response;
        if (list == null) {
            response = new TableResultResponse.Builder()
                    .message("无数据")
                    .total(0L)
                    .page(page)
                    .rows(null)
                    .build();
        } else {
            response = new TableResultResponse.Builder()
                    .message("分页查询结果")
                    .total(biz.count(wrapper))
                    .page(page)
                    .rows(list)
                    .build();
        }

        return response;
    }

    @GetMapping("/getByName")
    public ObjectRestResponse<SysMenu> getByName(SysMenu sysMenu){
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(sysMenu.getName())) {
            wrapper.lambda().eq(SysMenu::getName, sysMenu.getName());
        }
        if (sysMenu.getType() !=null && ( sysMenu.getType() == 1 || sysMenu.getType() ==  0)) {
            wrapper.lambda().eq(SysMenu::getType, sysMenu.getType());
        }
        return new ObjectRestResponse.Builder<SysMenu>().data(biz.getOne(wrapper)).status(200).message("查询成功!").build();
    }


    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping("/deleteBatch")
    public ObjectRestResponse<String> deleteBatch(String ids) {
        ObjectRestResponse<String> response = new ObjectRestResponse<>();
        try {
            /// 注意,当删除一个子菜单时,还要清除子菜单与之相关的pid值
            List<SysMenu> list = biz.list(new QueryWrapper<SysMenu>().lambda().in(SysMenu::getPid, ids));
            for (int i = 0; i <list.size() ; i++) {
                SysMenu menu = list.get(i);
                menu.setPid("");
                list.set(i, menu);
            }
            if (list.size() > 0) {
                biz.saveOrUpdateBatch(list, list.size());
            }
            /// 删除sysMenu表中的数据
            biz.removeByIds(Arrays.asList(ids.split(",")));
            /// 删除sysRoleMenu表中对应的数据
            sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>()
                    .in("menu_id",ids));
        } catch (Exception e) {
            response.setMessage("菜单批量删除:"+e.getMessage());
            response.setStatus(500);
            e.printStackTrace();
        }
        response.setMessage("批量删除成功!");
        return response;
    }

    @GetMapping("/getAllTreeNode")
    public ObjectRestResponse<SysUser> getAllTreeNode(){
        ObjectRestResponse<SysUser> response = new ObjectRestResponse<>();
        /// 从后台获取所有的菜单权限
        List<SysMenu> menuList = biz.list(new QueryWrapper<>());
        List<TreeNode> nodeList = new ArrayList<>(menuList.size()+1);
        List<TreeNode> list = new ArrayList<>();
        /// list集合 由SysMenu ---> TreeNode
        for (SysMenu sysMenu : menuList) {
            TreeNode treeNode = setTreeNode(sysMenu);
            nodeList.add(treeNode);
        }
        /// tree 生成
        for (int i = 0; i < nodeList.size() ; i++) {
            TreeNode node = nodeList.get(i);
            /// 判断顶级级点
            if (!StringUtils.isNotBlank(node.getPid())) {
                list.add(getTree(node, nodeList));
            }
        }
        SysUser sysUser = new SysUser();
        sysUser.setTreeNodeList(list);
        response.setData(sysUser);
        response.setMessage("权限树获取成功!");
        return response;
    }

    private TreeNode setTreeNode(SysMenu sysMenu) {
        TreeNode treeNode = new TreeNode();
        treeNode.setTitle(sysMenu.getName());
        treeNode.setLabel(sysMenu.getName());
        treeNode.setKey(sysMenu.getId());
        treeNode.setPid(sysMenu.getPid());
        treeNode.setId(sysMenu.getId());
        treeNode.setUrl(sysMenu.getUrl());
        treeNode.setSeq(sysMenu.getSeq());
        return treeNode;
    }

    private TreeNode getTree(TreeNode node, List<TreeNode> nodeList) {
        for (int i = 0; i <nodeList.size() ; i++) {
            TreeNode treeNode = nodeList.get(i);
            if (StringUtils.isNotBlank(treeNode.getPid()) && treeNode.getPid().equals(node.getId())) {
                node.getChildren().add(treeNode);
                getTree(treeNode, nodeList);
            }
        }
        return node;
    }
}

